package com.zwh.modules.listener;

import com.zwh.modules.scheduler.service.SchedulerJobService;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 实现spring的ContextRefreshedEvent spring 容器初始化bean加载完成后事件
 * @Author zwh
 * @Date 2019/11/1 15:13
 **/
@Configuration
public class ApplicationStartQuartzJobListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    SchedulerJobService schedulerJobService;

    /**
     * 初始启动quartz
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent()==null) {
            //系统会存在两个容器，一个是root application context ,另一个就是我们自己的 projectName-servlet context（作为root application context的子容器）
            //root application context 没有parent
            try {
                schedulerJobService.startJob();
                System.out.println("任务已经启动...");
            } catch (SchedulerException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 初始注入scheduler
     * @return
     * @throws SchedulerException
     */
    /*@Bean
    public Scheduler scheduler() throws SchedulerException {
        SchedulerFactory schedulerFactoryBean = new StdSchedulerFactory();
        return schedulerFactoryBean.getScheduler();
    }*/


}